const ms = require('ms')
const jwt = require('jsonwebtoken')
const Service = require('egg').Service

class AdminService extends Service {
  /**
   * 系统登录
   * @param {Object} options
   * @param {String} options.username
   * @param {String} options.password
   * @returns
   */
  async login(options) {
    const { ctx, config } = this
    const { md5 } = ctx.helper
    const { username, password } = options

    const admin = await ctx.model.Admin.findOne({
      username: username,
      password: md5(password),
    }).then((admin) => {
      if (!admin) throw '用户名或密码错误'

      return admin
    })

    const adminInfo = await this.getUserInfo(admin.adminId)

    // 签发token
    const token = jwt.sign(adminInfo, config.jwt.secret + 'admin', { expiresIn: config.jwt.expiresIn })

    const expireTime = Date.now() + ms(config.jwt.expiresIn)

    return {
      ...adminInfo,
      token,
      expireTime,
    }
  }

  /**
   * 获取用户信息
   * @param {*} adminId
   * @param {*} where
   * @returns
   */
  async getUserInfo(adminId) {
    const { ctx } = this

    const admin = await ctx.model.Admin.findOne({
      _id: adminId,
    }).then((admin) => {
      if (!admin) throw '用户不存在'
      if (!admin.isOpen) throw '账号已禁用'

      return admin
    })

    const adminRole = await ctx.model.AdminRole.findOne({
      _id: admin.roleId,
    }).then((adminRole) => {
      if (!adminRole) throw '用户暂未绑定角色'
      return adminRole
    })

    return {
      adminId: admin.adminId,
      username: admin.username,
      isAdmin: adminRole.isAdmin,
      roleId: adminRole.roleId,

      systemType: admin.systemType,
      sourceId: admin.sourceId,
    }
  }

  /**
   * 验证码用户名
   */
  async usernameVerify(username, adminId) {
    // 账户去重
    const filter = {
      username,
    }

    if (adminId)
      filter._id = {
        $ne: adminId,
      }

    await this.ctx.model.Admin.findOne(filter).then((admin) => {
      if (admin) throw '账号已被使用'
    })
  }

  /**
   * 验证码手机号
   */
  async mobileVerify(mobile, adminId) {
    if (mobile.length != 11) throw '手机号长度不正确'

    // 手机号去重
    const filter = {
      mobile,
    }

    if (adminId)
      filter._id = {
        $ne: adminId,
      }

    await this.ctx.model.Admin.findOne(filter).then((admin) => {
      if (admin) throw '手机号已被使用'
    })
  }
}

module.exports = AdminService
